<?php
/*
 * @Date: 2024-12-29 21:20:31
 */

namespace app\controller;

use app\BaseController;
use think\facade\View;
use app\middleware\Auth;
use think\exception\ValidateException;
use think\facade\Db;
use Tools\UEnv;
use Tools\Wt;

class Admin extends BaseController
{
    protected $middleware = [Auth::class];
    public function index()
    {
        if (!request()->isPost()) {
            View::assign(web_env());
            return View::fetch();
        }
        switch ($this->request->param("action")) {
            case "setUsername":
                try {
                    validate([
                        'username' => 'require',
                    ])->message([
                        'username.require' => '用户名不能为空',
                    ])->check([
                        'username' => $this->request->param('username')
                    ]);
                } catch (ValidateException $e) {
                    return json(['code' => 0, 'msg' => $e->getError()]);
                }
                UEnv::set("username", $this->request->param("username"));
                return json(['code' => 200, 'msg' => '设置成功']);
                break;
            case "setPassword":
                try {
                    validate([
                        'password' => 'require',
                    ])->message([
                        'password.require' => '密码不能为空',
                    ])->check([
                        'password' => $this->request->param('password')
                    ]);
                } catch (ValidateException $e) {
                    return json(['code' => 0, 'msg' => $e->getError()]);
                }
                UEnv::set("password", md5($this->request->param("password")));
                return json(['code' => 200, 'msg' => '设置成功']);
                break;
        }
    }

    public function main()
    {
        View::assign(web_env());
        View::assign("Usage_count", Db::table("auth")->sum('UsageCount'));
        View::assign("permission_count", Db::table("permission")->count());
        View::assign("true_count", Db::table("auth")->where('status','0')->whereTime("ExpirationTime","<",time())->count());
        View::assign("false_count", Db::table("auth")->where('status','1')->whereOr('ExpirationTime', '>', date('Y-m-d H:i:s'))->count());
        return View::fetch();
    }

    public function Config()
    {
        if (!request()->isPost()) {
            View::assign(web_env());
            return View::fetch();
        }
        switch ($this->request->param("action")) {
            case "set":
                UEnv::set("SystemName", $this->request->param("SystemName"));
                UEnv::set("SiteKeywords", $this->request->param("SiteKeywords"));
                UEnv::set("SiteDescription", $this->request->param("SiteDescription"));
                UEnv::set("icp", $this->request->param("icp"));
                UEnv::set("RandomSalt", $this->request->param("RandomSalt"));
                UEnv::set("ApiSwitch", $this->request->param("ApiSwitch"));
                return json(['code' => 200, 'msg' => '设置成功']);
                break;
            case "newToken":
                $time = time();
                UEnv::set("ApiToken", $time);
                $token = Wt::encrypt(["admin"], $time,  $time . UEnv::get("RandomSalt"));
                return json(['code' => 200, 'msg' => '设置成功', 'token' => $token]);
                break;
        }
    }

    public function AuthorizationManagement()
    {
        if (!request()->isPost()) {
            View::assign(web_env());
            View::assign("permission", Db::table("permission")->where("status", 0)->select()->toArray());
            return View::fetch();
        }
        switch ($this->request->param("action")) {
            case "list":
                if ($this->request->param("search") == "") {
                    $data = Db::table("auth")->order('id', $this->request->param("sortOrder"))->paginate([
                        'list_rows' => $this->request->param("limit"),
                        'page' => $this->request->param("page")
                    ]);
                } else {
                    $data = Db::table("auth")->where("username", "like", "%" . $this->request->param("search") . "%")->order('id', $this->request->param("sortOrder"))->paginate([
                        'list_rows' => $this->request->param("limit"),
                        'page' => $this->request->param("page")
                    ]);
                }
                return json([
                    "rows" => $data->items(),
                    "total" => $data->total()
                ]);
                break;
            case "add":
                try {
                    validate([
                        "email" => "require|email",
                        "end_time" => "require|date"
                    ])->message([
                        "email.require" => "邮箱不能为空",
                        "email.email" => "邮箱格式不正确",
                        "end_time.require" => "结束时间不能为空",
                        "end_time.date" => "结束时间格式不正确"
                    ])->check([
                        "email" => $this->request->param("email"),
                        "end_time" => $this->request->param("end_time")
                    ]);
                } catch (ValidateException $e) {
                    return json(['code' => 0, 'msg' => $e->getError()]);
                }
                $db = Db::table("auth")->where("email", $this->request->param("email"))->find();
                if ($db) {
                    return json(['code' => 0, 'msg' => '邮箱已存在']);
                    //邮箱存在
                } else {
                    Db::table("auth")->json(["permission_ider"])->insert([
                        "email" => $this->request->param("email"),
                        "ExpirationTime" => $this->request->param("end_time"),
                        "permission_ider" => $this->request->param("permission_ider")
                    ]);
                    return json(['code' => 200, 'msg' => '添加成功']);
                }
                break;
            case "get_user_info":
                $data = Db::table("auth")->where("id", $this->request->param("id"))->find();
                if (!$data) {
                    return json(['code' => 0, 'msg' => '获取失败']);
                }
                if ($data["permission_ider"]) {
                    $data["permission"] = Db::table("permission")->where("id", "in", json_decode($data["permission_ider"], true))->select()->toArray();
                    $data["permission_ider"] = json_decode($data["permission_ider"], true);
                } else {
                    $data["permission_ider"] = [];
                    $data["permission"] = [];
                }
                return json(['code' => 200, 'msg' => '获取成功', 'data' => $data]);
                break;
            case "set":
                if ($this->request->param("permission_ider")) {
                    $content = $this->request->param("content");
                    $content["permission_ider"] = json_encode($this->request->param("permission_ider"));
                    foreach ($this->request->param("ids") as $id) {
                        Db::table("auth")->where("id", $id)->json(["permission_ider"])->data($content)->update();
                    }
                }else{
                    foreach ($this->request->param("ids") as $id) {
                        Db::table("auth")->where("id", $id)->data($this->request->param("content"))->update();
                    }
                }
                return json(['code' => 200, 'msg' => '修改成功']);
                break;
        }
    }

    public function PermissionManagement()
    {
        if (!request()->isPost()) {
            View::assign(web_env());
            return View::fetch();
        }
        switch ($this->request->param("action")) {
            case "list":
                $data = Db::table("permission")->order('id', $this->request->param("sortOrder"))->paginate([
                    'list_rows' => $this->request->param("limit"),
                    'page' => $this->request->param("page")
                ]);
                return json([
                    "rows" => $data->items(),
                    "total" => $data->total()
                ]);
                break;
            case "set":
                foreach ($this->request->param("ids") as $id) {
                    Db::table("permission")->where("id", $id)->data($this->request->param("content"))->update();
                }
                return json(['code' => 200, 'msg' => '修改成功']);
                break;
            case "add":
                try {
                    validate([
                        "Identifier" => "require"
                    ])->message([
                        "Identifier.require" => "标识不能为空"
                    ])->check([
                        "Identifier" => $this->request->param("Identifier")
                    ]);
                } catch (ValidateException $e) {
                    return json(['code' => 0, 'msg' => $e->getError()]);
                }
                $sql = Db::table("permission")->where("Identifier", str_replace("/", "", $this->request->param("Identifier")))->find();
                if ($sql) return json(['code' => 0, 'msg' => '标识已存在']);
                Db::table("permission")->data([
                    "Identifier" => $this->request->param("Identifier"),
                    "Remark" => $this->request->param("Remark")
                ])->insert();
                return json(['code' => 200, 'msg' => '添加成功']);
                break;
            case "delete":
                foreach ($this->request->param("ids") as $id) {
                    Db::table("permission")->where("id", $id)->delete();
                }
                return json(['code' => 200, 'msg' => '删除成功']);
                break;
        }
    }

    public function login()
    {
        session('admin', null);
        $web_data = web_env();
        if (!request()->isPost()) {
            View::assign($web_data);
            return View::fetch();
        }
        try {
            validate([
                'username' => 'require',
                'password' => 'require',
                'captcha' => 'require|captcha'
            ])->message([
                'username.require' => '用户名不能为空',
                'password.require' => '密码不能为空',
                'captcha.require' => '验证码不能为空',
                'captcha.captcha' => '验证码错误'
            ])->check([
                'username' => $this->request->param('username'),
                'password' => $this->request->param('password'),
                'captcha' => $this->request->param('captcha')
            ]);
        } catch (ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }
        if ($this->request->param('username') != $web_data["username"]) return json(['code' => 0, 'msg' => '用户名错误']);
        if (md5($this->request->param('password')) != $web_data["password"]) return json(['code' => 0, 'msg' => '密码错误']);
        session('admin', "true");
        return json(['code' => 200, 'msg' => '登录成功']);
    }
}
